import glob
import json
import os
import time
import shutil
from datetime import datetime

import cv2
import numpy as np
import yaml

from log import logger

'''
加透明水印到图像上
'''
def add_watermark(image_path, text, position=(50, 50),
                  font=cv2.FONT_HERSHEY_SIMPLEX, font_scale=1, thickness=2,
                  watermark_color=(255, 255, 255), opacity=0.6):
    # 加载图片
    img = cv2.imread(image_path) if isinstance(image_path, str) else image_path
    # 创建一个与原图大小相同的空白图像用于绘制水印
    watermark = img.copy()
    # 在watermark上添加文本水印
    (text_width, text_height), _ = cv2.getTextSize(text, font, font_scale, thickness)
    x, y = position
    # 确保水印不越过图像边界
    if x + text_width > img.shape[1]:
        x = img.shape[1] - text_width - 10  # 调整x位置以避免超出右边
    if y - text_height < 0:
        y = text_height + 10  # 调整y位置以避免超出顶部

    cv2.putText(watermark, text, (x, y), font, font_scale, watermark_color, thickness, cv2.LINE_AA)
    # cv2.imwrite(output_path, watermark)
    # 将水印转换为带有透明度的效果
    alpha = opacity  # 设置透明度
    img = img * (1 - alpha) + watermark * alpha  # 速度?

    return img

def delete_directories_older_than_months(directory, months=3, ui_handle=None): # 20240625
    """
    删除指定目录下指定月份数以前的子目录及其内容。
    len(dir_name) == 8 and dir_name[:2] == '20' # 20240625

    :param directory: 要检查和清理的目录路径
    :param months: 要删除的目录的月份数
    """

    # 计算指定月份数之前的日期时间戳
    time_threshold = time.time() - (months * 30 * 24 * 60 * 60)

    for root, dirs, _ in os.walk(directory, topdown=False):  # topdown=False确保从子目录向上遍历
        for dir_name in dirs:
            if len(dir_name) == 8 and dir_name[:2] == '20': # 20240625
                dir_path = os.path.join(root, dir_name)
                # dir_mtime = os.path.getmtime(dir_path)
                # 根据文件夹名称计算时间戳
                # date_str = '20240625'
                date_format = '%Y%m%d'  # 定义日期字符串的格式
                dt_object = datetime.strptime(dir_name, date_format)# 将字符串转换为datetime对象
                dir_mtime = dt_object.timestamp()# 将datetime对象转换为时间戳
                # print(dir_path)
                # print(dir_mtime)
                if dir_mtime < time_threshold:

                    if ui_handle:
                        ui_handle.loginfo(f"删除文件夹: {dir_path}")
                    else:
                        logger.info(f"删除文件夹: {dir_path}")
                    try:
                        # os.rmdir(dir_path)  # 这里使用rmdir，它只能删除空目录
                        shutil.rmtree(dir_path) # 如果要递归删除非空目录，请使用shutil.rmtree
                    except OSError as e:
                        if ui_handle:
                            ui_handle.loginfo(f"删除文件夹错误: {e.filename} - {e.strerror}")
                        else:
                            logger.error(f"删除文件夹错误: {e.filename} - {e.strerror}")
def read_yaml(file_path):
    with open(file_path, 'r') as file:
        config = yaml.safe_load(file)
    return config


def write_yaml(data, file_path):
    with open(file_path, 'w') as file:
        yaml.safe_dump(data, file)

def get_ymdhmss(id=0):
    ct = time.time()+id
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y%m%d_%H%M%S", local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = "%s_%03d" % (data_head, data_secs)
    return time_stamp
def get_ymdhms(id=0):
    ct = time.time()+id
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y%m%d_%H%M%S", local_time)
    return data_head

def cv_imwrite(fn, src, quality=70):
    try:
        if not isinstance(src, np.ndarray):
            print(f'cv_imwrite: src is not ndarray ')
            return 0
        if min(src.shape)==0:
            print(f'cv_imwrite: min(src.shape={src.shape})==0 ')
            return 0
        fn1,ext = os.path.splitext(fn)
        if ext.lower() not in ['.png', '.bmp', '.jpg', '.jpeg']:
            ext = '.jpg'
        cv2.imencode(ext, src, params=[cv2.IMWRITE_JPEG_QUALITY, quality])[1].tofile(fn)
    except Exception as e:
        print(f'cv_imwrite err {str(e)}')
        pass
    return

def imshow(name, im, ms_time=-2, flag=0):
    cv2.namedWindow(name, flag)
    cv2.imshow(name, im)
    ret = 0
    if ms_time > -2:
        ret = cv2.waitKey(ms_time)
    return ret


# # 设置图片保存目录
# def get_outp2(index, end, save_dir, product):
#
#     ymd = time.strftime("%Y%m%d", time.localtime(time.time()))
#     end_str = 'ok' if end == 1 else 'ng'
#     outp = f'D:/data/save/{progname}/{ymd}/service{index}{end_str}/{product}'
#     product = f'{product}_{save_dir}'
#     outp = f'{d}/{product}'
#     mkdir(outp)
#     return outp
# def get_outp_hf(index, end):
#     ymd = time.strftime("%Y%m%d", time.localtime(time.time()))
#     end_str = 'ok' if end == 1 else 'ng'
#     outp = f'D:/data/save/{progname}/{ymd}/service{index}{end_str}'
#     mkdir(outp)
#     return outp
#
# def get_out_img_p0():
#     D = get_max_disk()
#     out_img_p = f'{D}:/data/save/{progname}'
#     return out_img_p


def get_date_stamp():
    ct = time.time()
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y%m%d", time.localtime(time.time()))
    return data_head


def change_rois_file(json_path='',target_names=[]):

    rois = {} # name:(x1y1x2y2)

    # load json

    with open(json_path, 'r') as load_f:
        content = json.load(load_f)

    for ind, t in enumerate(content['shapes']):

        ps = np.array(t['points']) # [(xy),(xy)]
        x1 = int(np.min(ps[:,0]))
        x2 = int(np.max(ps[:,0]))
        y1 = int(np.min(ps[:,1]))
        y2 = int(np.max(ps[:,1]))

        t['points'] = [[x1,1761-y2],[x2,1761-y1]] # 上下反转

    # 使用 json.dump 将 Python 对象保存为 JSON 文件
    with open(json_path, 'w', encoding='utf-8') as json_file:
        json.dump(content, json_file, ensure_ascii=False, indent=4)

    return rois

def t1():

    img_glob = r'config\rois\20241205_big15\*.jpg'
    ls = glob.glob(img_glob)
    for i in ls:
        img = cv2.imread(i)
        img00 = img[:, ::-1, :].transpose(1, 0, 2)[::-1, ...]

        cv2.imwrite(i, img00)

if __name__ == '__main__':

    # 使用示例
    # directory_to_clean = r'D:\data\save\fuba_tianxian'  # 替换为你要清理的目录路径
    # months_to_keep = 2 # 更改为你希望保留的月份数
    # delete_directories_older_than_months(directory_to_clean, months_to_keep)


    # change_rois_file(json_path= r'D:\code\git\project_format_jzbxh\config\rois\20241122_big1\ok_20241122_141609_896_ret1.json')
    t1()